<?php
declare(strict_types=1);

namespace App\Activity\Controller;

use App\Activity\Request\GroupActivityRequest;
use App\Activity\Service\ActivityService;
use App\Common\Constants\ErrorCode;
use App\Common\Controller\AbstractController;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * @Controller()
 */
class GroupActivityController extends AbstractController
{

    /**
     * @Inject()
     * @var ActivityService
     */
    private $actService;

    const GROUPACTIVITY = 0;

    /**
     * 获取拼团活动列表
     * @RequestMapping(path="/v1/activity/group", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function index(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = !empty($params['perpage']) ? $params['perpage'] : 15;
        $field = ['activityID', 'title', 'begin_date', 'end_date', 'activity_prams', 'status', 'create_at', 'shop_ids'];
        $res = $this->actService->getList($params, (int)$perPage, self::GROUPACTIVITY, $field);
        if (!$res['code']) {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 获取拼团活动详情
     * @RequestMapping(path="/v1/activity/{id:\d+}/group", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function info(int $id)
    {
        $field = ['activityID', 'title', 'activity_prams', 'begin_date', 'end_date', 'sort', 'image'];
        $res = $this->actService->getInfoById($id, self::GROUPACTIVITY, $field);
        if (!$res['code']) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 添加拼团活动
     * @PostMapping(path="/v1/activity/group", methods="post")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param GroupActivityRequest $request
     *
     * @return array
     */
    public function store(GroupActivityRequest $request)
    {
        $params = $request->validated();
        $res = $this->actService->add($params, self::GROUPACTIVITY);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 编辑团购活动
     * @PutMapping(path="/v1/activity/{id:\d+}/group", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     * @param GroupActivityRequest $request
     *
     * @return array
     */
    public function update(int $id, GroupActivityRequest $request)
    {
        $params = $request->validated();
        $params['id'] = $id;
        $res = $this->actService->update($params, self::GROUPACTIVITY);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 删除拼团活动
     * @DeleteMapping(path="/v1/activity/{id:\d+}/group", methods="delete")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     * @param RequestInterface $request
     *
     * @return array
     */
    public function delete(int $id)
    {
        $res = $this->actService->delete($id, self::GROUPACTIVITY);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 支付成功后开团
     * @PostMapping(path="/v1/activity/group/start", methods="post")
     */
    public function activityGroupStart()
    {
        $param = $this->request->all();
        if (empty($param['activity_id']) || empty($param['mid']) || empty($param['order_no'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->actService->activityGroupStart((int)$param['activity_id'], (int)$param['mid'], $param['order_no']);
        if ($res['code'] == 1) {
            return $this->success($res['data'], $res['msg']);
        }
        return $this->failed($res['errorCode'], $res['msg']);
    }


    /**
     * 支付成功后参团
     * @PostMapping(path="/v1/activity/group/join", methods="post")
     */
    public function activityGroupJoin()
    {
        $param = $this->request->all();
        if (empty($param['activity_id']) || empty($param['mid']) || empty($param['order_no']) || empty($param['groupNumber'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->actService->activityGroupJoin((int)$param['activity_id'], $param['groupNumber'], (int)$param['mid'], $param['order_no']);
        if ($res['code'] == 1) {
            return $this->success($res['data'], $res['msg']);
        }
        return $this->failed($res['errorCode'], $res['msg']);
    }

    /**
     * 可参团列表
     * @RequestMapping(path="/v1/activity/group/can", methods="get")
     */
    public function canJoinGroup()
    {
        $param = $this->request->all();
        if (empty($param['activity_id'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        if (!is_numeric($param['mid'])){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '登陆信息失效,请重新登陆噢');
        }
        $res = $this->actService->canJoinGroup((int)$param['activity_id'], (int)$param['mid']);
        if ($res['code'] == 1) {
            return $this->success($res['data'], $res['msg'], count($res['data']));
        }
        return $this->failed($res['errorCode'], $res['msg']);
    }

    /**
     * 参团信息
     * @RequestMapping(path="/v1/group/{groupNumber}", methods="get")
     * @param string $groupNumber
     * @return array
     */
    public function getGroupInfo(string $groupNumber)
    {
        $res = $this->actService->getGroupInfoByGroupNum($groupNumber);
        if ($res['code'] == 1) {
            return $this->success($res['data'], $res['msg']);
        }
        return $this->failed($res['errorCode'], $res['msg']);
    }


    /**
     * 好物拼团推荐
     * @RequestMapping(path="/v1/activity/group/recommend", methods="get")
     * @return array
     */
    public function recommendGroup()
    {
        $param = $this->request->all();
        if (!isset($param['shop_id']) || empty($param['shop_id'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $field = [
            'act.activityID',
            'act.activityType',
            'act.activity_prams',
            'ag.id as activity_goods_id',
            'ag.goods_id',
            'ag.goods_title',
            'ag.group_id',
            'ag.goods_logo',
            'ag.goods_spec',
            'ag.costprice',
            'ag.spell_num',
            'ag.price_selling'
        ];
        $res = $this->actService->getRecommendGroup($param, $field);
        if (isset($param['perpage']) && !empty($param['perpage'])) {
            return $this->success($res->items(), '获取拼团推荐成功', $res->total());
        } else {
            return $this->success($res, '获取拼团推荐成功', $res->count());
        }
    }

    /**
     * 申请退款后清除团购信息
     * @PostMapping(path="/v1/group/refund/remove", methods="post")
     * @return array
     */
    public function groupRefund()
    {
        $param = $this->request->all();
        if (empty($param['activity_id']) || empty($param['mid']) || empty($param['order_no'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->actService->refundRemoveGroupInfo((int)$param['activity_id'], (int)$param['mid'], $param['order_no']);
        if ($res['code'] == 1) {
            return $this->success([], $res['msg']);
        }
        return $this->failed($res['errorCode'], $res['msg']);
    }


    /**
     * 拼团成功信息播报
     * @RequestMapping(path="/v1/activity/group/broadcast", methods="get")
     * @return array
     */
    public function broadcast(){
        $param = $this->request->all();
        if (!is_numeric($param['activity_id']) || !is_numeric($param['mid'])) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        // 拼团成功播报
        $res = $this->actService->broadcast((int) $param['activity_id'], (int) $param['mid']);
        return $this->success($res, '获取播报成功', count($res));
    }

    /**
     * 获取拼团商品详情
     *
     * @RequestMapping(path="/v1/api/activity/{id:\d+}/group", methods="get")
     * @param int $id
     *
     * @return array
     */
    public function groupActivityInfo(int $id)
    {
        $filed = [
            'id as activity_goods_id',
            'activityID',
            'goods_id',
            'goods_title',
            'goods_logo',
            'goods_spec',
            'group_id',
            'costprice',
            'price_selling',
            'stock',
            'spell_num',
        ];
        $res = $this->actService->GetActivityInfoByActivityId($id, $filed);
        return $this->success($res, '获取拼团商品详情成功', count($res));
    }


    /**
     * 获取限时抢购列表
     *
     * @RequestMapping(path="/v1/api/activity/flash_sale", methods="get")
     *
     * @param RequestInterface $request
     * @return array
     */
    public function flashSaleList(RequestInterface $request)
    {
        $shop_id = $request->input('shop_id');
        if (!$shop_id) {
            return $this->failed(ErrorCode::PARAMS_INVALID, '参数错误或缺少参数');
        }
        $res = $this->actService->getSaleFlashList($shop_id);
        return $this->success($res, '获取成功');
    }

    /**
     * 获取限时抢购列表
     *
     * @RequestMapping(path="/v1/api/activity/{id:\d+}/flash_sale/detail", methods="get")
     *
     * @param RequestInterface $request
     * @return array
     */
    public function activityListItems($id,RequestInterface $request)
    {
        $shop_id = $request->input('shop_id');
        if (!$shop_id) {
            return $this->failed(ErrorCode::PARAMS_INVALID, '参数错误或缺少参数');
        }
        $res = $this->actService->detailInfo($id, $shop_id);
        return $this->success($res, '获取成功');
    }
}
